package com.lyd.controller;

import com.lyd.domain.Emp;
import com.lyd.dto.EmpDto;
import com.lyd.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    private EmpService empService;


    /**
     * 查询所有
     *
     * @return
     */
    @RequestMapping("/getAll")
    public ModelAndView getAll() {
        ModelAndView mv = new ModelAndView();
        List<Emp> empList = empService.getAll();
        mv.addObject("empList", empList);
        mv.setViewName("emp");
        return mv;
    }


    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping("/getOneById/{id}")
    public ModelAndView getOneById(@PathVariable Long id) {
        ModelAndView mv = new ModelAndView();
        Emp emp = empService.getOneById(id);
        mv.addObject("EmpOneById", emp);
        mv.setViewName("emp");
        return mv;
    }

    /**
     * 新增
     * @param dto
     * @return
     */
    @Transactional
    @PostMapping("/addOne")
    public ModelAndView addOne(  EmpDto dto) {
        ModelAndView mv = new ModelAndView();

        Emp emp = new Emp();
        emp.setEname(dto.getEname());
        emp.setEage(dto.getEage());
        emp.setEphone(dto.getEphone());
        empService.addOne(emp);

        mv.addObject("newEmp", emp);
        mv.setViewName("addSuccess");

        /*事务测试*/
        /*int a=1/0;

        Emp emp2 = new Emp();
        emp2.setEname(dto.getEname());
        emp2.setEage(dto.getEage());
        emp2.setEphone(dto.getEphone());
        empService.addOne(emp2);*/

        return mv;
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @Transactional
    @RequestMapping("/delById/{id}")
    public ModelAndView delById(@PathVariable Long id) {
        ModelAndView mv = new ModelAndView();
        Emp emp = empService.getOneById(id);
        mv.setViewName("delSuccess");
        mv.addObject("delEmp", emp);
        empService.delById(id);
        return mv;
    }


    /**
     * 根据id修改
     * @param dto
     * @return
     */
    @Transactional
    @PostMapping(value = "/updById")
    public ModelAndView updById( EmpDto dto) {

        ModelAndView mv = new ModelAndView();
        Emp oldEmp = empService.getOneById(dto.getId());

        mv.addObject("oldEmp",oldEmp);
        mv.addObject("newEmp",dto);
        mv.setViewName("updSuccess");

        empService.updById(dto);

        return mv;
    }






}
